"""
Kafka相关API路由
"""
from typing import List, Dict, Any
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel

from app.core.kafka_client import get_kafka_client
from app.utils.logger import get_logger

router = APIRouter()
logger = get_logger(__name__)


class KafkaConnectionTest(BaseModel):
    """Kafka连接测试响应"""
    success: bool
    message: str
    brokers: int = 0


class TopicInfo(BaseModel):
    """Topic信息"""
    name: str
    partitions: int
    partition_info: List[Dict[str, Any]]


@router.get("/connection/test", response_model=KafkaConnectionTest)
async def test_kafka_connection():
    """测试Kafka连接"""
    try:
        kafka_client = get_kafka_client()

        # 使用智能连接测试
        result = await kafka_client.test_connection_with_fallback()

        return KafkaConnectionTest(
            success=result["success"],
            message=result["message"],
            brokers=result.get("brokers", 0)
        )
    except Exception as e:
        logger.error(f"测试Kafka连接失败: {e}")
        return KafkaConnectionTest(
            success=False,
            message=f"连接测试失败: {str(e)}",
            brokers=0
        )


@router.get("/topics", response_model=List[str])
async def list_topics():
    """获取Topic列表"""
    try:
        kafka_client = get_kafka_client()
        topics = await kafka_client.list_topics()
        return topics
    except Exception as e:
        logger.error(f"获取Topic列表失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取Topic列表失败: {str(e)}")


@router.get("/topics/{topic_name}", response_model=TopicInfo)
async def get_topic_info(topic_name: str):
    """获取Topic详细信息"""
    try:
        kafka_client = get_kafka_client()
        topic_meta = await kafka_client.get_topic_metadata(topic_name)
        
        if topic_meta is None:
            raise HTTPException(status_code=404, detail=f"Topic不存在: {topic_name}")
        
        return TopicInfo(**topic_meta)
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取Topic信息失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取Topic信息失败: {str(e)}")


@router.get("/cluster/info")
async def get_cluster_info():
    """获取集群信息"""
    try:
        kafka_client = get_kafka_client()
        metadata = await kafka_client.get_cluster_metadata()

        if metadata is None:
            raise HTTPException(status_code=500, detail="无法获取集群元数据")

        return {
            "cluster_id": metadata.get("cluster_id"),
            "controller_id": metadata.get("controller_id"),
            "brokers": metadata.get("brokers", [])
        }
    except Exception as e:
        logger.error(f"获取集群信息失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取集群信息失败: {str(e)}")
